<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item prop="status">
        <el-select v-model="queryParams.status" placeholder="客户状态..." clearable>
          <el-option v-for="dict in dict.type.sys_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item prop="type">
        <el-select v-model="queryParams.type" placeholder="客户类型..." clearable>
          <el-option v-for="dict in dict.type.customer_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item prop="source">
        <el-select v-model="queryParams.source" placeholder="客户来源..." clearable>
          <el-option v-for="item in links" :key="item.id" :label="item.name"
            :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item prop="keywords">
        <el-input v-model="queryParams.keywords" placeholder="请输入关键词" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['customer:customer:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['customer:customer:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['customer:customer:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-s-promotion" size="mini" @click="handleSplit"
          v-hasPermi="['customer:customer:export']">分配</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-remove" size="mini" @click="handleMove"
          v-hasPermi="['customer:customer:export']">放入公海</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange" @row-click="openShow"
      highlight-current-row ref="customerTable" @current-change="handleCurrentChange" style="cursor: pointer;">

      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户编号" align="center" prop="number" width="150" />

      <el-table-column label="客户头像" align="center" prop="avatar" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50" @click.native.stop="openShow(scope.row, 1)" />
        </template>
      </el-table-column>

      <el-table-column label="客户姓名" align="center" prop="name" />
      <el-table-column label="客户昵称" align="center" prop="nickname" />
      <el-table-column label="手机号码" align="center" prop="phone" />
      <el-table-column label="余额" align="center" prop="balance" />

      <el-table-column label="客户来源" align="center" prop="sourceName" />
      <el-table-column label="推荐人" align="center" width="150">
        <template slot-scope="scope">
          <span style="color: red;">{{ scope.row.parentName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="绑定商机" align="center" width="150">
        <template slot-scope="scope">
          <span :style="{
            color: scope.row.oppNums > 0 ? 'blue' : '#000',
            textDecoration: scope.row.oppNums > 0 ? 'underline' : 'none',
            cursor: scope.row.oppNums > 0 ? 'pointer' : 'default',
          }" @click.stop.prevent="scope.row.oppNums > 0 && getOpps(scope.row.id, scope.row.oppNums)">
            {{ scope.row.oppNums || 0 }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_type" :value="scope.row.type" />
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="注册时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['customer:customer:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['customer:customer:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改客户列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="客户头像" prop="avatar">
          <image-upload v-model="form.avatar" :limit="1" />
        </el-form-item>

        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入客户姓名" />
        </el-form-item>

        <el-form-item label="客户昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入客户昵称" />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-tabs v-model="activeName" type="card" @tab-click="handleClick" v-show="showTabs">
      <el-tab-pane label="基本信息" name="first">
        <basicInfo :info="basic"></basicInfo>
      </el-tab-pane>

      <el-tab-pane label="团队成员" name="second">
        <el-tabs :tab-position="tabPosition" style="height: 200px;" @tab-click="handleTabClick" v-model="activeTab">
          <el-tab-pane :label="item.cname" v-for="(item, index) in proList" :name="item.id.toString()">
            <teamList :list="empList" :total="e_total" :loading="e_loading"></teamList>
          </el-tab-pane>
        </el-tabs>
      </el-tab-pane>

      <el-tab-pane label="浏览痕迹" name="third">
        <viewList :list="viewList" :total="v_total" :loading="v_loading"></viewList>
      </el-tab-pane>

      <el-tab-pane label="跟进记录" name="fourth">
        <followList :list="followList" :total="f_total" :loading="f_loading"></followList>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<script>
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer, getProList, getEmpList, getViewList, getFollowList } from "@/api/customer/customer"
import {ALlLinks} from "@/api/share/links"
import basicInfo from "./components/basicInfo.vue"
import teamList from "./components/teamList.vue"
import viewList from "./components/viewList.vue"
import followList from "./components/followList.vue"

export default {
  name: "Customer",
  components: {
    basicInfo,
    teamList,
    viewList,
    followList  // 注册组件
  },
  dicts: ['customer_type', 'sys_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户列表表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keywords: null,
        status: null,
        type: null,
        createTime: null,
        startTime: null,
        endTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nickname: [{
          required: true,
          message: "昵称不能为空",
          trigger: "blur"
        }],
        name: [{
          required: true,
          message: "姓名不能为空",
          trigger: "blur"
        }],
        phone: [{
          required: true,
          message: "手机号不能为空",
          trigger: "blur"
        }]
      },
      activeName: 'first',
      showTabs: false,
      basic: {},
      dateRange: [],
      currentRow: null,
      lastClickedRow: null, // 记录上次点击的行
      tabPosition: 'left',
      proList: [],
      empList: [],
      viewList: [],
      followList: [],
      crmId: 0,
      activeTab: '', // tab当前选中的name,需要是字符串
      // 遮罩层 团队员工
      e_loading: true,
      // 总条数 团队员工
      e_total: 0,
      // 遮罩层 浏览记录
      v_loading: true,
      // 总条数 浏览记录
      v_total: 0,
      // 遮罩层 跟进记录
      f_loading: true,
      // 总条数 跟进记录
      f_total: 0,
      links:[]
    }
  },
  created() {
    this.getList()
    this.getLinks()
  },
  methods: {

    // 获取客户跟进记录
    getLinks() {
      ALlLinks().then(response => {
        this.links = response.rows
      })
    },


    handleSplit(){
      console.log('分配操作')
    },

    handleMove(){
      console.log('移入公海')
    },


    // 查看商机明细
    getOpps(id, nums) {
      if (nums == 0) {
        return
      }

      this.showTabs = true
      this.activeName = 'second'
      this.crmId = id
      this.getProList(id)
    },

    handleTabClick(tab) {
      const proId = tab.name; // 获取点击的标签页的name
      this.getTeams(proId);
    },

    // 根据达人id获取团队成员
    getTeams(id) {
      this.empList = []
      this.getEmpList(this.crmId, id)
    },

    // 处理当前行变化
    handleCurrentChange(currentRow, oldCurrentRow) {
      this.currentRow = currentRow;
    },

    // 清除选中高亮行
    clearCurrentRow() {
      this.$refs.customerTable.setCurrentRow();
      this.currentRow = null;
      this.lastClickedRow = null;
    },
    // 点击某一行打开详情
    openShow(row, none) {
      // 如果是点击头像放大，不唤起详情
      if (none == 1) {
        return
      }
      // 判断是否是点击同一行
      if (this.lastClickedRow && this.lastClickedRow.id === row.id) {
        // 点击同一行，取消高亮
        this.clearCurrentRow();
        this.showTabs = false
        console.log('取消高亮');
      } else {

        // 点击不同行，设置高亮并打开详情
        this.$refs.customerTable.setCurrentRow(row);
        this.lastClickedRow = row;

        // 记录当前选中客户id
        this.crmId = row.id
        this.showTabs = true;
        this.getBasic(row.id)
        this.activeName = 'first'
      }

    },

    // 获取机构达人列表
    getProList(id) {
      getProList(id).then(response => {
        this.proList = response.data
        if (response.data.length != 0) {
          let tab_id = response.data[0].id
          this.activeTab = tab_id.toString()
          this.getEmpList(id, tab_id)
        }

      })
    },

    // 获取客户跟进记录
    getFollowList(id) {
      this.f_loading = true
      getFollowList(id).then(response => {
        this.followList = response.rows
        this.f_total = response.total
        this.f_loading = false
      })
    },


    getViewList(id) {
      this.v_loading = true
      getViewList(id).then(response => {
        this.viewList = response.rows
        this.v_total = response.total
        this.v_loading = false
      })
    },


    // 获取员工列表
    getEmpList(id, proId) {
      this.e_loading = true
      getEmpList(id, proId).then(response => {
        this.empList = response.rows
        this.e_total = response.total
        this.e_loading = false
      })
    },

    getBasic(id) {
      getCustomer(id).then(response => {
        this.basic = response.data
      })
    },
    // tab顶部切换
    handleClick(tab, event) {
      // 根据 activeName 获取当前激活的 tab-pane
      console.log('当前激活的 tab-pane name:', this.activeName)
      let id = this.crmId

      // 你可以根据 activeName 执行相应的逻辑
      switch (this.activeName) {
        case 'first':
          this.getBasic(id)
          // 基本信息 tab 的逻辑
          break
        case 'second':
          this.getProList(id)

          // 团队成员 tab 的逻辑
          break
        case 'third':
          this.getViewList(id)

          // 浏览痕迹 tab 的逻辑
          break
        case 'fourth':
          this.getFollowList(id)
          // 跟进记录 tab 的逻辑
          break
      }

    },
    /** 查询客户列表列表 */
    getList() {
      this.loading = true
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        parentId: null,
        grandparentId: null,
        type: null,
        number: null,
        nickname: null,
        avatar: null,
        name: null,
        phone: null,
        source: null,
        remark: null,
        balance: null,
        status: null,
        createTime: null,
        deleteTime: null,
        expTime: null,
        op: null,
        firstTime: null,
        tag: null,
        isBlack: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.startTime = this.dateRange[0]
      this.queryParams.endTime = this.dateRange[1]
      this.queryParams.pageNum = 1
      this.showTabs = false
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.showTabs = false

      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加客户"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCustomer(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改客户"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除客户列表编号为"' + ids + '"的数据项？').then(function () {
        return delCustomer(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('customer/customer/export', {
        ...this.queryParams
      }, `customer_${new Date().getTime()}.xlsx`)
    },
  }
}
</script>
